#include "userwidget.h"
#include <QtXml>
#include <QtGui>

#define ROLE_TYPE Qt::UserRole + 2
#define ROLE_UIN  Qt::UserRole + 3

#define TYPE_USER 1

UserWidget::UserWidget(UMSDatabase *dbase)
{
	setupUi(this);
	
	_userModel = new QStandardItemModel();
	_userModel->setHorizontalHeaderItem(0,new QStandardItem(trUtf8("Список пользователей")));
	treeView->setModel(_userModel);
	connect(treeView->selectionModel(),SIGNAL(currentChanged(QModelIndex,QModelIndex)),SLOT(userChanged(QModelIndex,QModelIndex)));
	splitter->setSizes(QList<int>() << 250 << 1000);
	QString fname = QSettings().value("last_file_dbusers","").toString();
	/*if(QFile::exists(fname)){
		loadUsersFromFile(fname);
	}*/
	_uusers = new UMSUsers(dbase);
	loadUsers();
	
}


UserWidget::~UserWidget()
{
	delete _uusers;
}

void UserWidget::loadUsers()
{
	QMap<QString,QString> users = _uusers->users();

	QMap<QString, QString>::const_iterator i = users.constBegin();
	_userModel->clear();
	QStandardItem *item = 0;
	while (i != users.constEnd()){
		QStandardItem *xitem = appendUserToTree(i.key(),i.value());
		if(item==0) item=xitem;
		++i;
	}	
	if(item!=0){
		treeView->setCurrentIndex(_userModel->indexFromItem(item));
	}
}

void UserWidget::setUserNode(QDomElement elem)
{
	setUserName(elem.firstChildElement("name").text());
}

void UserWidget::setUserName(const QString &username)
{
	editUser->setText(username);
	_username = username;
}

QString UserWidget::user()
{
	return editUser->text();	
}

void UserWidget::on_pbRemoveUser_clicked()
{
	QModelIndex index = treeView->currentIndex();
	if(!index.isValid()) return;
	QStandardItem *item = _userModel->itemFromIndex(index);
	if(!item) return;
	_uusers->removeUser(item->text());
	loadUsers();
}

void UserWidget::on_pbSave_clicked()
{
	QModelIndex index = treeView->currentIndex();
	if(!index.isValid()) return;
	QStandardItem *item = _userModel->itemFromIndex(index);
	if(!item) return;
	QString olduname = item->text();
	_uusers->removeUser(olduname);
	User u;
	u.login = editUser->text();
	u.passwd = editPasswd->text();
	u.cert = editSert->text();
	u.fam = editFam->text();
	u.name = editName->text();
	u.otch = editFatherName->text();
	for(int i=0;i<listAddrs->count();i++){
		u.hosts << listAddrs->item(i)->text();
	}
	for(int i=0;i<listDatabases->count();i++){
		u.bases << listDatabases->item(i)->text();
	}
	_uusers->newUser(&u);
	loadUsers();
	selectUser(u.login);
}

void UserWidget::selectUser(const QString &uname)
{
	QModelIndex index;
	for(int i=0;i<_userModel->rowCount();i++){
		if(_userModel->item(i)->text()==uname){
			index = _userModel->indexFromItem(_userModel->item(i));
			break;
		}
	}
	treeView->setCurrentIndex(index);
}

void UserWidget::loadUsersFromFile(const QString &fname)
{
	_userFileName = fname;
	QFile file(fname);
	if(!file.open(QIODevice::ReadOnly)){
		QMessageBox::warning(this,trUtf8("Ошибка"),trUtf8("Ошибка открытия файла %1").arg(file.fileName()));
		return;
	}
	
	if(!_docUsers.setContent(&file)){
		QMessageBox::warning(this,trUtf8("Внимание"),trUtf8("Ошибка структуры файла %1").arg(file.fileName()));
	}else{
		loadUsers(_docUsers);
	}
	file.close();	
}

void UserWidget::loadUsers(const QDomDocument &doc)
{
	QDomElement root = doc.firstChildElement("ums");
	if(root.isNull()){
		QMessageBox::warning(this,trUtf8("Внимание"),trUtf8("Отсутвует тег UMS."));
		return;
	}
	QDomElement elem = root.firstChildElement("user");
	if(elem.isNull()){
		QMessageBox::warning(this,trUtf8("Внимание"),trUtf8("Отсутвуют пользователи в структуре."));
	}
	while(!elem.isNull()){	
		//appendUserToTree(nodeValue("name",elem));
		elem = elem.nextSiblingElement();
	}
	QApplication::processEvents();
}

QStandardItem *UserWidget::appendUserToTree(const QString &uin,const QString &name)
{
	QStandardItem *item = new QStandardItem(trUtf8("%1").arg(name));		
	item->setFlags(item->flags() & ~Qt::ItemIsEditable);
	item->setData(TYPE_USER,ROLE_TYPE);		
	item->setData(uin,ROLE_UIN);
	item->setIcon(QIcon(":icons/images/icons/user.png"));
	_userModel->appendRow(item);
	//on_pbSave_clicked();
	return item;
}

QString UserWidget::nodeValue(const QString &name,const QDomElement &root)
{
	return root.firstChildElement(name).text();
}

QDomElement UserWidget::userNode(const QString &name)
{
	QDomElement root = _docUsers.firstChildElement("ums");
	QDomElement elem = root.firstChildElement("user");
	while(!elem.isNull()){	
		if(nodeValue("name",elem)==name){
			return elem;
		}
		elem = elem.nextSiblingElement();
	}
	return QDomElement();
}

bool UserWidget::hasUserName(const QString &uname)
{
	QMap<QString,QString> users = _uusers->users();
	QMap<QString, QString>::const_iterator i = users.constBegin();
	while (i != users.constEnd()){		
		if(i.value()==uname) return true;
		++i;
	}	
	return false;	
}

void UserWidget::on_pbAddUser_clicked()
{
	QString uname;
	for(int i=1;;i++){
		uname = QString("user%1").arg(i);
		if(!hasUserName(uname)) break;
	}
	if(uname.isEmpty()){
		QMessageBox::warning(this,trUtf8("Ошибка"),trUtf8("Не определено имя для нового пользователя."));
		return;
	}
	//_uusers->newUser(uname);
	QStandardItem *item = appendUserToTree("0.0",uname);
	if(!item) return;
	treeView->setCurrentIndex(_userModel->indexFromItem(item));
	
	//loadUsers();
	//QStandardItem *item = newUserToTree("user");
	//treeView->edit(_userModel->indexFromItem(item));
	pbSave->setEnabled(true);
}

void UserWidget::createNewUser()
{
	on_pbAddUser_clicked();
}

void UserWidget::userChanged(const QModelIndex &current,const QModelIndex &/*prev*/)
{
	QStandardItem *item = _userModel->itemFromIndex(current);
	if(!item) return;
	QString username = item->text();
	
	editUser->setText(username);
	editPasswd->setText("12345678");
	listDatabases->clear();
	listAddrs->clear();
	//reeditPasswd->setText("12345678");
	User *u=0;
	u = _uusers->user(username);
	if(u==0) return;
	
	editSert->setText(u->cert);
	editFam->setText(u->fam);
	editName->setText(u->name);
	editFatherName->setText(u->otch);
	
	foreach(QString dbase,u->bases)
	{
		addDatabaseInList(dbase);
	}
	
	foreach(QString addr,u->hosts)
	{
		addHostInList(addr);
	}
}

void UserWidget::on_pbUpdate_clicked()
{
	loadUsers();
}

QListWidgetItem *UserWidget::addDatabaseInList(const QString &name)
{
	QListWidgetItem *item = new QListWidgetItem(name);
	item->setFlags(item->flags() | Qt::ItemIsEditable);	
	listDatabases->addItem(item);
	return item;
}

QListWidgetItem *UserWidget::addHostInList(const QString &name)
{
	QListWidgetItem *item = new QListWidgetItem(name);
	item->setFlags(item->flags() | Qt::ItemIsEditable);	
	listAddrs->addItem(item);
	return item;
}

void UserWidget::on_pbAddBase_clicked()
{
	QListWidgetItem *item = addDatabaseInList("database");	
	listDatabases->editItem(item);
}

void UserWidget::on_pbAddAddr_clicked()
{
	QListWidgetItem *item = addHostInList("127.0.0.1");	
	listAddrs->editItem(item);
}

void UserWidget::on_pbRemoveBase_clicked()
{
	QListWidgetItem *item = listDatabases->currentItem();
	//qDebug() <<Q_FUNC_INFO<< "Item" << item;
	if(!item){
		qDebug() <<Q_FUNC_INFO<< "no item";
		return;
	}
	//listDatabases->removeItemWidget(item);
	delete listDatabases->takeItem(listDatabases->row(item));
}

void UserWidget::on_pbRemoveAddr_clicked()
{
	QListWidgetItem *item = listAddrs->currentItem();
	//qDebug() <<Q_FUNC_INFO<< "Item" << item;
	if(!item){
		qDebug() <<Q_FUNC_INFO<< "no item";
		return;
	}
	//listDatabases->removeItemWidget(item);
	delete listAddrs->takeItem(listAddrs->row(item));
}
